package com.frame.pageform;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class JsonServlet  extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private String charset ="GBK";

	public void init() throws ServletException
	{

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws
			ServletException, IOException
	{
		process(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws
			ServletException, IOException
	{
		process(request, response);
	}
	private void process(HttpServletRequest request,
						 HttpServletResponse response) throws ServletException, IOException
	{
		try{
			String pagePath=request.getRequestURI().replaceFirst("\\.json", "");
			String contextPath=request.getContextPath();
			if(contextPath!=null && !"".equals(contextPath))
				pagePath=pagePath.replaceFirst(contextPath, "");

			//设置上下文
			RequestContext requestContext = new RequestContext(request, response,this);
			PageBeanUtil pageutil=new PageBeanUtil();
			PageForm pageform=requestContext.getPageForm();
			if(pageform==null)
				pageform=pageutil.createPageForm(pagePath);
			String json="";
			if(pageform!=null){
				try {
					//填充表单
					pageutil.fillParameter(pageform, request.getParameterMap(),request.getContentType(),charset);
					requestContext.setPageForm(pageform);
					json=pageform.execute();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
			response.setContentType("text/json;charset=utf-8");
			PrintWriter out=response.getWriter();
			out.print(json);
			out.flush();
			out.close();
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			RequestContext.clear();
		}
	}
}
